/**
	Grid封装
*/
Ext.namespace('Ext.publics'); 
Ext.publics.ListGridPanel = function(viewer, config) {
    this.viewer = viewer;
    if(!config) config = {};
    Ext.apply(this, config);
	this.serverurl = pageparam.url ? pageparam.url : 'business!queryPage.action';
    this.httpProxy = new Ext.data.HttpProxy({url : this.serverurl});
	var title = pageparam.title;
	var defines = pageparam.defines;
	var forceFitFlag = true;
	 if (pageparam.forceFitFlag == false){
	 	forceFitFlag = pageparam.forceFitFlag;
	 }
	
	this.busi = pageparam.businame;
	if(config.hidebbar) pageRowCount = 0;
	this.loadColumns(defines,pageRowCount);
	
	var pagingBar = new Ext.PagingToolbar({
		plugins : [new Ext.ux.grid.PageSizePlugin(),new Ext.ux.ProgressBarPager()],
        pageSize: pageRowCount,
        store: this.store,
        displayInfo: true
    });
    this.pagingBar = pagingBar;
    if(!config.hidebbar) this.bbar = pagingBar;
    
    //默认工具条
    var tbar = [' 关键字搜索: ', ' ',
	           	new Ext.ux.form.SearchField({
	                grid: this,
	                width:220
	           }), '-', {
				text : '刷新',
				iconCls : 'arrow_refresh',
				handler : function() {
					store.reload();
				}
			}, '->',{
				text : '新增',
				iconCls : 'application_add',
				handler : function() {
					Ext.getCmp("cardWindow").show();
				}
			}, '-', {
				text : '修改',
				iconCls : 'application_edit',
				handler : function() {
					editInit();
				}
			}, '-', {
				text : '删除',
				iconCls : 'application_delete',
				handler : function() {
					deleteDeptItems('1', '');
				}
			}  ];
    
    var sm = new Ext.grid.CheckboxSelectionModel();
 	Ext.publics.ListGridPanel.superclass.constructor.call(this, {
        region: 'center',
        margins:'2 2 2 2',
        stripeRows:true,
        loadMask: {msg:title},
        enableColumnHide:false,
        autoExpandColumn : 'remark',
        title : '<span class="commoncss">' + title + '</span>',
        tbar:tbar,
        sm: sm,
        viewConfig: {
        	forceFit:forceFitFlag,
            enableRowBody:true,
            showPreview:true,
            getRowClass : this.applyRowClass
        }
    });
	
	this.on('rowdblclick', this.openWindow, this);
	this.getSelectionModel().on("rowselect",this.selectRow, this);
	this.addEvents("rowselect");
};

Ext.extend(Ext.publics.ListGridPanel, Ext.grid.GridPanel, {
	selectedUpIndex : null,
	selectRow : function(sm,rowIndex,record){
		this.selectedUpIndex = rowIndex;
	},
	getSelected:function( _b ){
		var _sm = this.getSelectionModel() ;
		
		if(_sm.getCount() == 0)
		{
			if (_b)
			{
				_sm.selectFirstRow();
			}
			else
			{
				throw Error("请选择一行！") ;
			}
		}
		
		return _sm.getSelected() ;
	},
	loadColumns : function ( ataglist  ,apageSize)
    {
    	if (!apageSize) apageSize = 10;
		if (apageSize==-1) apageSize = 0;
    	var cmarray = [new Ext.grid.RowNumberer(),new Ext.grid.CheckboxSelectionModel()];
    	var rdarray = [];
    	if (ataglist){
	    	for (var i=0;i<ataglist.length;i++){
	    		var cmobj = {};
	    		var rdobj = {};
	    		
	    		var oname = ataglist[i];
	    		if (typeof(oname)=='object'){
	    			cmobj.header = oname.name;
		        	cmobj.dataIndex = oname.name;
		        	if (oname.width) cmobj.width = oname.width * 1;
		        	if (oname.id) cmobj.id = oname.id;
		        	if (oname.hidden) cmobj.hidden = oname.hidden;
		        	if (oname.renderer) cmobj.renderer = oname.renderer;
		        	if (oname.align) cmobj.align = oname.align;
		        	if (oname.locked) cmobj.locked = oname.locked;
		        	rdobj.name = oname.name;
		        	var _grid = this;
	    		}else{
			        cmobj.header = oname;
			        cmobj.dataIndex = oname;
			        cmobj.width =120;
			        rdobj.name = oname;
	    		}
	    		
	    		cmobj.sortable = true;
		        cmarray.push(cmobj);
		        rdarray.push(rdobj);
	    	}
    	}
    	
    	if (rdarray.length>0){
    		this.reader = new Ext.data.ArrayReader({
										root:"rows",
										totalProperty  :"count"
								   },rdarray)
    	}
    	
    	var cjson = Ext.util.JSON.encode(pageparam.busiobj);
    	this.store = new Ext.data.Store({
    			autoLoad :{params : {start : 0,limit : apageSize}},
    			baseParams: {queryConfig:cjson},
	            proxy: this.httpProxy,
	            reader : this.reader
	    });
	    this.rplant = rdarray;
	    this.columns = cmarray;
    },
    ReturnNewPlant : function ()
    {
    	if (!this.rplant) {return;}
    	var plant = Ext.data.Record.create(this.rplant);
    	return plant;
    },
    replaceStore : function ( _busiobj , _reader)
    {
    	var cjson = Ext.util.JSON.encode(_busiobj);
	    var store = new Ext.data.GroupingStore({
	    		autoLoad :{params : {start : 0,limit : pageRowCount}},
    			baseParams: {queryConfig:cjson},
	            proxy: this.httpProxy,
	            reader : _reader
		    });
	    return store;
    },
    
    replaceColumns : function ( ataglist  )
    {
    	var cmarray = [new Ext.grid.RowNumberer(),new Ext.grid.CheckboxSelectionModel()];
    	var rdarray = [];
    	if (ataglist)
    	{
	    	for (var i=0;i<ataglist.length;i++)
	    	{
	    		var cmobj = {};
	    		var rdobj = {};
	    		
	    		var oname = ataglist[i];
	    		if (typeof(oname)=='object')
	    		{
	    			if (oname.name=="data_id") oname.name="ID";
	    			cmobj.header = oname.name;
		        	cmobj.dataIndex = oname.name;
		        	if (oname.width) cmobj.width = oname.width * 1;
		        	if (oname.id) cmobj.id = oname.id;
		        	if (oname.hidden) cmobj.hidden = oname.hidden;
		        	if (oname.renderer) cmobj.renderer = oname.renderer;
		        	if (oname.align) cmobj.align = oname.align;
		        	if (oname.locked) cmobj.locked = oname.locked;
		        	rdobj.name = oname.name;
		        	var _grid = this;
	    		}
	    		else
	    		{
	    			if (oname=="data_id") oname="ID";
			        cmobj.header = oname;
			        cmobj.dataIndex = oname;
			        cmobj.width =120;
			        rdobj.name = oname;
	    		}
	    		
	    		cmobj.sortable = true;
	    		if (cmobj.dataIndex == "ID") cmobj.hidden = true;
		        cmarray.push(cmobj);
		        rdarray.push(rdobj);
	    	}
    	}
    	if (rdarray.length>0){
    		this.reader = new Ext.data.ArrayReader({
										root:"rows",
										totalProperty  :"count"
								   },rdarray)
    	}
    	var store = this.replaceStore(pageparam.busiobj,this.reader);
    	this.replaceBbar(store);
		this.reconfigure(store,new Ext.grid.ColumnModel(cmarray));
    	//return new Ext.grid.ColumnModel(cmarray);
    },
    
    replaceBbar : function ( _store )
    {
    	if (!_store) {return;}
		this.pagingBar.bind(_store);
    },
    
	onRowSelect:function(_sel , _index , _r){
		this.fireEvent("rowselect" , _r) ;
	},
	remove:function(delAttFlag,delAttRootPath){
		try{
			var id = "";
			var _sr = this.getSelectionModel().getSelections();
			for(var i=0;i<_sr.length;i++){
				if(id) id += ",";
				id += "'" + _sr[i].get("ID") + "'";
			}
			var _kind = pageparam.businame;
			var cond = "data_id in(" +  id + ")";
			var _params = {
				bname : _kind,
				cond : cond,
				option : "del",
				delAllAttachmentFlag : delAttFlag,
				delAllAttachmentRootPath : delAttRootPath
			}
			var jsonArray = {};
			jsonArray.jsons = Ext.encode([_params]);
			Ext.Ajax.request({url:"/WDB/server/public/busicard_Array_Ext.jsp" , params:jsonArray}) ;
			for(var i=0;i<_sr.length;i++){
				this.getStore().remove(_sr[i]) ;
			}
			
			this.getView().refresh();
			
			Ext.Msg.alert("系统提示" , "删除成功！") ;
		}catch(_err){
			Ext.Msg.alert("系统提示" , _err.description) ;
		}
	},
	update:function(data,record){
		try{
			var Plant = this.ReturnNewPlant();
			var _r = null;
			if (Plant){_r = new Plant(data);}
			var _sr = this.getSelected();
			if(record)
				_sr = record;
			if (_r && _sr)
			{
				var _data = _r.data ;
				for(var _i in _data){
					_sr.set(_i , _r.get(_i)) ;
				}
				_sr.commit() ;
				this.fireEvent("rowselect" , _sr) ;
			}
		}catch(_err){
		}
	},
	add:function(data){
		var Plant = this.ReturnNewPlant();
		var _sr = null;
		if (Plant){_sr = new Plant(data);}
		if (_sr)
		{
			this.getStore().add(_sr);
			_sr.commit() ;
			this.fireEvent("rowselect" , _sr) ;
		}
	},
	onRemoveGridList:function(delAttachmentFlag,delAttachmentRootPath){
		var delAttFlag = delAttachmentFlag ? delAttachmentFlag : true;
		var delAttRootPath = delAttachmentRootPath ? delAttachmentRootPath : (ajax.fileRoot);
		delAttRootPath = delAttRootPath.replace(/\\/g,"/");
		var selects = this.getSelectionModel().getSelections();
        if(selects.length == 0) {
    		Ext.Msg.alert("系统提示","你尚未选定一条记录") ;
    	} else {
    		Ext.Msg.confirm("系统提示" , "你确定删除这 <span style='color:red;font-weight:bold;'>"+selects.length+"</span> 条记录?" , 
    			function(_but){if(_but=='yes') this.remove(delAttFlag,delAttRootPath) ;} , this) ;
    	}
    	
	},
	onRemoveClear : function (_btn) {
		if (_btn == "yes")
		{
            var _kind = pageparam.businame;
			var _params = {
				bname : _kind,
				cond : "",
				option : "del"
			}
			var jsonArray = {};
			jsonArray.jsons = Ext.encode([_params]);
			
			Ext.Ajax.request({url:"/WDB/server/public/busicard_Array_Ext.jsp" , params:jsonArray}) ;
			this.getStore().removeAll();
		}
	},
	openWindow : function(_grid){
		loadformfill();
	},
	searchData : function(){
		var cjson = Ext.util.JSON.encode(pageparam.busiobj);
		this.store.baseParams = {queryConfig:cjson};
		this.store.load({params : {start : 0,limit : pageRowCount }});
	},
	findRecordById : function(dataid)
	{
		var gridStore = this.getStore();
		var index = gridStore.findBy(function(record, id) 
		{
			return record.get('ID') == dataid ;
		});
		return gridStore.getAt(index);
	}
});

Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
    readRecords : function(o){
        var sid = this.meta ? this.meta.id : null;
    	var recordType = this.recordType, fields = recordType.prototype.fields;
    	var records = [];
    	var root = this.meta ? this.meta["root"] ? o[this.meta["root"]] : o : o;
	    for(var i = 0; i < root.length; i++){
		    var n = root[i];
	        var values = {};
	        var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
	        for(var j = 0, jlen = fields.length; j < jlen; j++){
                var f = fields.items[j];
                var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
                var v = n[k] !== undefined ? n[k] : f.defaultValue;
                v = f.convert(v, n);
                values[f.name] = v;
            }
	        var record = new recordType(values, id);
	        record.json = n;
	        records[records.length] = record;
	    }
	    return {
	        records : records,
	        totalRecords : this.meta ? this.meta["totalProperty"] ? o[this.meta["totalProperty"]] : records.length : records.length
	    };
    }
});
